package com.banciyuan.bcywebview.biz.apprecommend;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.MineInfo;
import de.greenrobot.daoexample.model.RecommendPersonData;

/**
 * Created by hy on 2015/7/10.
 */
public class RecommendPersonNewActivity extends BaseActivity implements View.OnClickListener {

    private RequestQueue mQueue;
    private ImageLoader imageLoader;
    private PopupWindow mPopWindow;
    private ProgressBar pbIng;
    private ImageView ivDone;
    private TextView tvDesc;
    private LinearLayout llPersonData;
    private TextView next;

    private List<RecommendPersonData> list = new ArrayList<>();
    private View mProgressbarView;
    private ProgressbarHelper mProgressbarHelper;

    private List<TextView> tvStatuses = new ArrayList<>();
    private List<LinearLayout> persones = new ArrayList<>();
    private List<TextView> tvCancleStatuses = new ArrayList<>();
    private Map<String, String> userMaps = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newpersonrecommend);
        initArgs();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }


    @Override
    protected void initUi() {
        next = (TextView) findViewById(R.id.tv_next_step);
        TextView tvTitleSencond = (TextView) findViewById(R.id.tv_title_sencond);
        tvTitleSencond.setText(getString(R.string.play_with_our));
        llPersonData = (LinearLayout) findViewById(R.id.ll_persondata);
        next.setSelected(true);
    }

    @Override
    protected void initAction() {
        next.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + UserApi.getLeaduser();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, RecommendPersonNewActivity.this)) {
                        JSONObject result = new JSONObject(response);
                        Gson gson = new Gson();
                        list = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<RecommendPersonData>>() {
                        }.getType());
                        processData();
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                }
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
            }
        };
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSuccess, onError);
        mQueue.add(stringRequest);
    }


    private void processData() {
        tvStatuses.clear();
        persones.clear();
        tvCancleStatuses.clear();
        userMaps.clear();
        mProgressbarHelper.onSuccess();
        llPersonData.removeAllViews();
        processFirstPersonData();
        for (int i = 0; i < list.size(); i++) {
            RecommendPersonData recommendPersonData = list.get(i);
            final View itemView = View.inflate(this, R.layout.recommendnewperson_item, null);
            TextView tvPersonName = (TextView) itemView.findViewById(R.id.tv_name);
            final LinearLayout llPerson = (LinearLayout) itemView.findViewById(R.id.ll_person);
            final TextView tvStatus = (TextView) itemView.findViewById(R.id.tv_status);
            final TextView tvStatusCancle = (TextView) itemView.findViewById(R.id.tv_status_cancle);
            tvStatuses.add(tvStatus);
            persones.add(llPerson);
            tvCancleStatuses.add(tvStatusCancle);
            tvPersonName.setText(recommendPersonData.getName());
            boolean firstChangeStatus = true;
            for (int j = 0; j < recommendPersonData.getUsers().size(); j++) {
                MineInfo mineInfo = recommendPersonData.getUsers().get(j);
                final View innerItemView = View.inflate(this, R.layout.recommend_person_item, null);
                ImageView ivHead = (ImageView) innerItemView.findViewById(R.id.civ_head);
                TextView tvName = (TextView) innerItemView.findViewById(R.id.tv_name);
                final ImageView ivSelected = (ImageView) innerItemView.findViewById(R.id.iv_selected);
                String followstate = mineInfo.getFollowstate();
                if (StringUtil.notNullEqual(followstate, "unfollow")) {
                    ivSelected.setVisibility(View.INVISIBLE);
                    firstChangeStatus = false;
                } else {
                    ivSelected.setVisibility(View.VISIBLE);
                }
                final MineInfo finalMineInfo = mineInfo;
                ivHead.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ivSelected.setVisibility(View.VISIBLE);
                        userMaps.put(finalMineInfo.getUid(), "follow");
                        finalMineInfo.setFollowstate("follow");
                        boolean changeStatus = true;
                        for (int k = 0; k < llPerson.getChildCount(); k++) {
                            boolean shown = llPerson.getChildAt(k).findViewById(R.id.iv_selected).isShown();
                            if (shown) {
                                continue;
                            } else {
                                changeStatus = false;
                            }
                        }
                        if (changeStatus) {
                            tvStatus.setVisibility(View.INVISIBLE);
                            tvStatusCancle.setVisibility(View.VISIBLE);
                        }
                    }
                });
                ivSelected.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ivSelected.setVisibility(View.INVISIBLE);
                        userMaps.put(finalMineInfo.getUid(), "unfollow");
                        finalMineInfo.setFollowstate("unfollow");
                        tvStatus.setVisibility(View.VISIBLE);
                        tvStatusCancle.setVisibility(View.INVISIBLE);
                    }
                });
                imageLoader.displayImage(mineInfo.getAvatar(), ivHead, ImageOptions.optionHead);
                tvName.setText(mineInfo.getUname());
                llPerson.addView(innerItemView);
            }
            if (firstChangeStatus) {
                tvStatus.setVisibility(View.INVISIBLE);
                tvStatusCancle.setVisibility(View.VISIBLE);
            }
            llPersonData.addView(itemView);
        }
        if (persones.size() == tvStatuses.size() && persones.size() == tvCancleStatuses.size()) {
            for (int i = 0; i < persones.size(); i++) {
                final LinearLayout person = persones.get(i);
                final TextView tvStatus = tvStatuses.get(i);
                final TextView tvCancleStatus = tvCancleStatuses.get(i);
                final int finalI = i;
                tvStatuses.get(i).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int j = 0;
                        for (; j < person.getChildCount(); j++) {
                            person.getChildAt(j).findViewById(R.id.iv_selected).setVisibility(View.VISIBLE);
                            String uid = list.get(finalI).getUsers().get(j).getUid();
                            userMaps.put(uid, "follow");
                        }
                        tvStatus.setVisibility(View.INVISIBLE);
                        tvCancleStatus.setVisibility(View.VISIBLE);
                    }
                });
                tvCancleStatuses.get(i).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int j = 0;
                        for (; j < person.getChildCount(); j++) {
                            person.getChildAt(j).findViewById(R.id.iv_selected).setVisibility(View.INVISIBLE);
                            String uid = list.get(finalI).getUsers().get(j).getUid();
                            userMaps.put(uid, "unfollow");
                        }
                        tvStatus.setVisibility(View.VISIBLE);
                        tvCancleStatus.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }
    }


    private void processFirstPersonData() {
        boolean needSeletedDefault = true;
        for (int i = 0; i < list.size(); i++) {
            RecommendPersonData recommendPersonData = list.get(i);
            for (int j = 0; j < recommendPersonData.getUsers().size(); j++) {
                String followstate = recommendPersonData.getUsers().get(j).getFollowstate();
                if (!"unfollow".equals(followstate)) {
                    needSeletedDefault = false;
                }
            }
        }
        if (needSeletedDefault && list.size() > 0) {
            List<MineInfo> users = list.get(0).getUsers();
            for (int i = 0; i < users.size(); i++) {
                users.get(i).setFollowstate("follow");
                userMaps.put(users.get(i).getUid(), "follow");
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_next_step:
                doLikes();
                break;
        }
    }

    private void doLikes() {
        if (!userMaps.keySet().isEmpty()) {
            doPop();
            String url = HttpUtils.BASE_URL + UserApi.getMultifollow();
            List<BcyPair> paramsList = new ArrayList<>();
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
            paramsList.add(new BcyPair(HttpUtils.UPLOAD_DATA, new Gson().toJson(userMaps)));
            HashMap<String, String> params = HttpUtils.getData(paramsList);
            Response.Listener<String> onSucc = new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        if (StatusCodeUtils.dealStatusCode(s, RecommendPersonNewActivity.this)) {
                            showcomplate();
                        } else {
                            goNext();
                        }
                    } catch (Exception e) {
                        MyToast.show(RecommendPersonNewActivity.this, getResources().getString(R.string.bcy_net_error));
                        goNext();
                    }
                }
            };

            Response.ErrorListener onError = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    MyToast.show(RecommendPersonNewActivity.this, getResources().getString(R.string.bcy_net_error));
                    goNext();
                }
            };
            StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, onError);
            mQueue.add(stringRequest);
        } else {
            goNext();
        }
    }

    private void showcomplate() {
        pbIng.setVisibility(View.INVISIBLE);
        ivDone.setVisibility(View.VISIBLE);
        tvDesc.setText(getString(R.string.done_success));
        llPersonData.postDelayed(new Runnable() {
            @Override
            public void run() {
                goNext();
            }
        }, 500);
    }

    private void goNext() {
        if (null != mPopWindow && mPopWindow.isShowing() && !this.isFinishing()) {
            mPopWindow.dismiss();
        }
        gotoUtil.replaceMainClearTop(RecommendPersonNewActivity.this);
        finish();
        SPHelper.putBoolean(RecommendPersonNewActivity.this, SPConstant.BCY_SHOWRECOMMEND, true);
    }

    private void doPop() {
        View contentView = View.inflate(this, R.layout.pop_mark_acg, null);
        mPopWindow = new PopupWindow(contentView,
                -1, -1,
                true);
        mPopWindow.setContentView(contentView);
        pbIng = (ProgressBar) contentView.findViewById(R.id.pb_ing);
        ivDone = (ImageView) contentView.findViewById(R.id.iv_done);
        tvDesc = (TextView) contentView.findViewById(R.id.tv_desc);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.showAtLocation(next, Gravity.LEFT + Gravity.TOP,
                0, 0);
    }

    @Override
    public void onBackPressed() {

    }
}
